package com.travel.server.manager.impl.dal;

import com.travel.common.exception.WorkCode;
import com.travel.common.exception.WorkException;
import com.travel.server.manager.dao.MemberGradeInfoDao;
import com.travel.server.manager.model.MemberGradeInfo;
import com.travel.server.manager.model.MemberGradeInfoExample;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @Author: LiZhenhui
 * @Date: 2018/11/9 18:39
 * @Desc:
 */
@Component
@Slf4j
public class MemberGradeDal {

    @Autowired
    private MemberGradeInfoDao memberGradeInfoDao;

    public List<MemberGradeInfo> selectByExample(MemberGradeParam param){
        if(param == null){
            param = new MemberGradeParam();
        }
        MemberGradeInfoExample example = makeExample(param);

        return memberGradeInfoDao.selectByExample(example);
    }

    public Integer insertOrUpdate(MemberGradeInfo memberGradeInfo){
        if(memberGradeInfo.getId() == null){
            memberGradeInfoDao.insertSelective(memberGradeInfo);
        }else{
            memberGradeInfoDao.updateByPrimaryKey(memberGradeInfo);
        }
        return memberGradeInfo.getId();
    }

    public MemberGradeInfo selectById(Integer id){
        MemberGradeInfo memberGradeInfo = memberGradeInfoDao.selectByPrimaryKey(id);
        if(memberGradeInfo == null){
            log.error("未查询到会员等级记录, id {}", id);
            throw new WorkException(WorkCode.RECORD_NOT_EXIST);
        }
        return memberGradeInfo;
    }

    private MemberGradeInfoExample makeExample(MemberGradeParam param){
        MemberGradeInfoExample example = new MemberGradeInfoExample();
        MemberGradeInfoExample.Criteria criteria = example.createCriteria();
        if(StringUtils.isNotBlank(param.getName())){
            criteria.andNameEqualTo(param.getName());
        }
        if(param.getState() != null){
            criteria.andStateEqualTo(param.getState());
        }
        if(param.getLimit() != null && param.getOffset() != null){
            example.setLimit(param.getLimit());
            example.setOffset(param.getOffset());
        }
        return example;
    }

    @Data
    public static class MemberGradeParam{
        private String name;

        private Integer state = 1;

        private Integer limit;

        private Integer offset;
    }
}
